package com.lc;


import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * 自定义的线程池类
 *
 */
public class MyThreadPool {
    //任务队列
    private List<Runnable> tasks = Collections.synchronizedList(new LinkedList<Runnable>());
    //当前线程数量
    private int num;
    //核心线程数
    private int corePoolSize;
    //最大线程数
    private int maxSize;
    //任务队列长度
    private int workSize;

    private int aa;

    public MyThreadPool(int corePoolSize, int maxSize, int workSize) {
        this.corePoolSize = corePoolSize;
        this.maxSize = maxSize;
        this.workSize = workSize;
    }


    //提交任务
    public void submit(Runnable runnable){
        //判断当前集合中任务数量是否超出了最大任务数量
        if(tasks.size() >= workSize){
            System.out.println("任务："+runnable+"被丢弃了");
        }else{
            tasks.add(runnable);
            exceTask(runnable);

        }
    }

    //执行任务
    //当任务过多时，相当于创建四条线程去执行任务队列里的任务，由于集合（队列）是线程安全的，所以不会重复执行
    private void exceTask(Runnable runnable) {
        //判断当前线程池中的线程总数量，是否超出了核心数
        if(num < corePoolSize){
            new MyWorker("核心线程："+num, tasks).start();
            num ++;
        }else if(num < maxSize){
            new MyWorker("非核心线程："+ num, tasks).start();
            num++;
        }else {
            System.out.println("任务："+ runnable +"被缓存了");
        }
    }
}
